import { Http } from "./http"

class Paging {
    //不关心细节
    //我需要下一页数据，你能给我吗
    //状态   实例化
    req
    start
    count
    //锁  默认值 没有锁住
    locker = false
    url
    moreData = true
    accumulator = []

    constructor(req, count = 10, start = 0) {
        this.req = req
        this.start = start
        this.count = count
        this.url = req.url

    }

    //生成器 Generator
    async getMoreData() {
        if (!this.moreData) {
            return
        }
        //request
        if (!this._getLocker) {
            return
        }
        const data = await this._actualGetData()
        this._releaseLocker()
        return data

    }

    async _actualGetData() {
        const req = this._getCurrentReq();

        let paging = await Http.localRequest(req);
        if (!paging) {
            return null
        }
        if (paging.total === 0) {
            return {
                empty: true,
                items: [],
                moreData: false,
                //累加器
                accumulator: []
            }
        }
        this.moreData = this._moreData(paging.total_page, paging.page)
        if (this.moreData) {
            this.start += this.count

        }
        this._accumulate(paging.items)
        return {
            empty: false,
            items: paging.items,
            moreData: this.moreData,
            //累加器
            accumulator: this.accumulator
        }
    }
    //数组合并
    _accumulate(items) {
        this.accumulator = this.accumulator.concat(items)
    }

    _moreData(totalPage, pageNum) {
        return pageNum < totalPage - 1
    }
    _getCurrentReq() {
        let url = this.url
        const params = `start=${this.start}&count=${this.count}`
        // url = v1/spu/latest +'?'+ params
        // url = v1/spu/latest?other=abc+'& ' +params

        if (url.includes('?')) {
            url += '&' + params
        } else {
            url += '?' + params
        }
        this.req.url = url
        return this.req

    }

    _getLocker() {
        if (this.locker) {
            return false
        }
        this.locker = true
        return true
    }

    _releaseLocker() {
        this.locker = false
    }


}
export {
    Paging
}